#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

int beginIndex,maxLength;
int check(int a[], int use[], int length, int curIndex, int *nextPtr, int laseOne)
{
	if(curIndex >= length)
	{
		*nextPtr = -1;
		return 0;
	}

	int useLength;
	if( laseOne < a[curIndex] )
		useLength = use[curIndex];
	else
		useLength = -1;

	int unUseLength = check( a, use, length, curIndex+1, nextPtr, laseOne );

	if(useLength >= unUseLength )
	{
		*nextPtr = curIndex;
		return useLength;
	}
	else
	{
		return  unUseLength;
	}


}

void mainFunc(int a[], int use[], int unUse[], int indexs[], int length)
{
	use[length-1] = 1;
	unUse[length-1] = 0;
	indexs[length-1] = -1;
	beginIndex = length-1;
	maxLength = 1;


	for(int i=length-2; i>-1; i-- )
	{
		use[i] = 1 + check(a, use, length,i+1, indexs+i, a[i]);
		unUse[i] = unUse[i+1]>use[i+1] ? unUse[i+1] : use[i+1];

		if(use[i] >= maxLength)
		{
			beginIndex = i;
			maxLength = use[i];
		}
	}
}

int main()
{
	/*	
	int a[] = {7,8,9,10,1,2,3,4};
	
	int unUse[3000];
	int use[3000];
	int indexs[3000];

	mainFunc(a, use, unUse,indexs,sizeof(a)/sizeof(a[0]));

	int index = beginIndex;
	while( index != -1)
	{
		printf("%d ", a[index]);
		index = indexs[index];
	}
	return 0;*/

	int caseNum;
	cin>>caseNum ;
	{

		int *array = new int[3000];
		int *inUseArray = new int[3000];
		int *unUseArray = new int[3000];
		int *indexs = new int[3000];
		int number;
		for(int i=0; i<caseNum; i++)
		{
			scanf("%d", &number);
			for(int j=0; j<number; j++ )
			{
				scanf("%d", array+j);
			}

			mainFunc(array, inUseArray, unUseArray,indexs,number);

			int index = beginIndex;
			while( index != -1)
			{
				if(indexs[index] != -1 )
					printf("%d ", array[index]);	
				else
					printf("%d\n", array[index]);
								
				index = indexs[index];
			}
		}
	}
	return 0;
}
